<template>
  <div :class="active === data.id ? '__active' : ''" @click.stop.preve="onClick(data)" class="afast-tree-node">
    <div class="label" :style="{ paddingLeft: level * 5 + 'px' }">
      <slot :data="data"></slot>
      <div v-if="!useSlots().default" class="text">{{ data.label }}</div>
      <AfastIcon @click="showChilren = !showChilren" v-if="data.children && data.children.length > 0" class="down"
        :class="showChilren ? 'reverse' : ''" name="down"></AfastIcon>
    </div>
    <div class="chilren" v-show="showChilren">
      <div v-for="node in data.children" :key="node.id">
        <AfastTree @update:active="onActive" :active="active" @click="onClick" :level="level + 1" :data="node">
          <template v-if="useSlots().default" #default="n: any">
            <slot :data="n.data"></slot>
          </template>
        </AfastTree>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, useSlots } from 'vue';
import AfastIcon from './AfastIcon.vue';
const emit = defineEmits(['click', 'update:active'])
const onActive = (id: number | string) => {
  active.value = id
  emit('update:active', id)
}
const onClick = (data: TreeNode) => {
  onActive(data.id)
  emit('click', data)
}
const showChilren = ref(false)
const props = withDefaults(defineProps<{
  data: TreeNode,
  level?: number,
  active?: number | string
}>(), {
  level: 0
})
const active = ref<number | string | undefined>(props.active)
watch(() => props.active, (id: number | string | undefined, oldId: number | string | undefined) => {
  if (oldId !== id || active.value !== id) {
    active.value = id
  }
})
</script>
<style lang="less">
.afast-tree-node {
  cursor: pointer;
  user-select: none;
  background: var(--afast-tree-bg-color);
  min-width: 100px;

  .label {
    display: flex;
    align-items: center;
    width: 100%;
    overflow: hidden;
    box-sizing: border-box;

    .text {
      margin-left: 10px;
    }

    .down {
      margin-left: 10px;
      transition: 0.2s;
    }

    .down.reverse {
      transform: rotate(180deg);
      transition: 0.2s;
    }
  }
}

.afast-tree-node:hover {
  background: var(--afast-tree-hover-bg-color);
}

.afast-tree-node.__active {
  background: var(--afast-tree-active-bg-color);
}
</style>